/**
 * Copyright (C) 2016-2017 Hangzhou Elabcare Co. Ltd.
 * All right reserved.
 *
 * @author: Simon.lee
 * date: 2017-09-26 14:43
 */
package com.mt.roll.core.utils;

import okhttp3.*;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.ssl.TrustStrategy;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

/**
 * 使用 OKhttp 请求 Api 数据
 */
public class HttpClient {

    private static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    public static String httpGet(String url) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        Response response = httpClient.newCall(request).execute();
        // 返回的是string 类型，json的mapper可以直接处理
        return response.body().string();
    }

    public static String httpPost(String url, String json) throws IOException {
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody requestBody = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        Response response = httpClient.newCall(request).execute();
        return response.body().string();
    }

    public static String httpPost(String postUrl, String soapXml, String token) throws Exception {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
        HttpPost httpPost = new HttpPost(postUrl);
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        if (StringUtils.isNotEmpty(token)) {
            httpPost.setHeader("X-Authorization", "Bearer " + token);
            httpPost.setHeader("x-requested-with", "XMLHttpRequest");
        }
        StringEntity data = new StringEntity(soapXml,
                Charset.forName("UTF-8"));
        httpPost.setEntity(data);
        CloseableHttpResponse response = closeableHttpClient
                .execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        if (httpEntity != null) {
            // 打印响应内容
            retStr = EntityUtils.toString(httpEntity, "UTF-8");
        }
        // 释放资源
        closeableHttpClient.close();
        return StringEscapeUtils.unescapeHtml4(retStr);
    }

    public static String httpExpressPost(String postUrl, String soapXml, String token) throws Exception {
        String retStr = "";
        // 创建HttpClientBuilder
        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        // HttpClient
        CloseableHttpClient closeableHttpClient = getIgnoeSSLClient();
        HttpPost httpPost = new HttpPost(postUrl);
        httpPost.setHeader("Content-type", "application/json; charset=utf-8");
        httpPost.setHeader("token", token);
        StringEntity data = new StringEntity(soapXml,
                Charset.forName("UTF-8"));
        httpPost.setEntity(data);
        CloseableHttpResponse response = closeableHttpClient
                .execute(httpPost);
        HttpEntity httpEntity = response.getEntity();
        if (httpEntity != null) {
            // 打印响应内容
            retStr = EntityUtils.toString(httpEntity, "UTF-8");
        }
        // 释放资源
        closeableHttpClient.close();
        return StringEscapeUtils.unescapeHtml4(retStr);
    }

    /**
     * 获取忽略证书验证的client
     *
     * @return
     * @throws Exception
     */

    public static CloseableHttpClient getIgnoeSSLClient() throws Exception {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();

        //创建httpClient
        CloseableHttpClient client = HttpClients.custom().setSSLContext(sslContext).
                setSSLHostnameVerifier(new NoopHostnameVerifier()).build();
        return client;
    }
}
